package cn.itcast.anli.web;

import cn.itcast.anli.domain.Employee;
import cn.itcast.anli.service.EmployeeService;
import cn.itcast.anli.service.impl.EmployeeServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@WebServlet("/modifyServlet")
public class ModifyServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        //获取员工id
        Employee employee = new Employee();
        Map<String, String[]> map = request.getParameterMap();
        try {
            BeanUtils.populate(employee,map);
        } catch (Exception e) {
            //输入错误时，传递输入错误信息到request域中，并跳转回添加页面
            request.setAttribute("int_error","数据输入格式有误！请重新填写！");
            request.getRequestDispatcher("/modify.jsp").forward(request,response);
            return;
        }
        String joindate = request.getParameter("date");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date date = null;
        try {
            date = sdf.parse(joindate);
        } catch (ParseException e) {
            //入职日期未填写，传递输入错误信息到request域中，并跳转回添加页面
            request.setAttribute("date_error","入职日期未选择！请重新选择！");
            request.getRequestDispatcher("/modify.jsp").forward(request,response);
            return;
        }
        employee.setJoindate(date);
        //调用Service对象的相关方法
        EmployeeService service = new EmployeeServiceImpl();
        service.modify(employee);
        //修改完之后，跳转到列表页面
        response.sendRedirect(request.getContextPath()+"/findEmpByPageServlet");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
